using Silvery.Data;
using System.Windows.Controls;
using System.Windows;
using System;
namespace Silvery.Loader
{
    /// <summary>
    /// 精灵读取类
    /// </summary>
    public class SpiritLoader : ZIPLoader
    {
        public SpiritLoader(ISpirit spirit = null)
        {
            SpiritItem = spirit;
        }
        //直接设定的外部数据
        protected ISpirit SpiritItem;
        public SpiritLoader(Uri uri,ISpirit spirit = null)
            : base(uri)
        {            
            SpiritItem = spirit;
        }
        
        protected override void LoadCompleted(IResStream stream)
        {
            base.LoadCompleted(stream);
            SpiritData = Create(this);
            if (SpiritItem != null)
            {
                //带入过来的Item，所以用完了就在这里面释放掉
                SpiritItem.SpiritData = SpiritData;
                SpiritItem = null;
            }
        }
        public ISpiritData SpiritData { get; protected set; }
        
        protected virtual ISpiritData Create(Loader.IZIPLoader data)
        {
            NSpiritData spiritdata = new NSpiritData();

            var framesinfo = data.GetTextStreamFormZipPack(SpiritFile_Frames.FileName);
            var datatable = new SpiritFile_Frames();
            datatable.Load(framesinfo);
            var framenames = datatable.FrameNames;
            foreach (var item in framenames)
            {
                if (datatable.Attributes.ContainsKey(item))
                    continue;
                var bitmap = data.GetImageFormZipPack(item);
                Image img = new Image() { Source = bitmap };
                Point offsetpoint = new Point()
                {
                    X = Convert.ToDouble(datatable[item, SpiritFile_Frames.OffsetX]),
                    Y = Convert.ToDouble(datatable[item, SpiritFile_Frames.OffsetY])
                };
                img.Tag = offsetpoint;
                var aniname = datatable[item, SpiritFile_Frames.AniName];

                spiritdata.AddFrame(aniname, img);            
            }
            spiritdata.FramesInfo = datatable;
            return spiritdata;
        }
        public override void Dispose()
        {
            SpiritData = null;
            SpiritItem = null;
            base.Dispose();
        }
    }
}
